 package cn.itcast.bos.action.base.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.base.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Controller
@Scope("prototype")
@Namespace("/")
/**
 * 宣传活动的相关方法
 * @author 艾欣
 *
 */
public class PromotionAction extends BaseAction<Promotion> {
	// 属性驱动
	private File titleImgFile;
	private String titleImgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	// 注入业务层
	@Autowired
	private PromotionService ps;

	// 保存宣传图片
@Action(value="promotion_save",results={@Result(name="success",type="redirect",location="./pages/take_delivery/promotion.html")})
	public String save() throws IOException {
	//保存图片的真是路径
	String realPath = ServletActionContext.getServletContext().getRealPath("/upload/");
	//展示图片的相对路径
	String saveurl = ServletActionContext.getRequest().getContextPath()+"/upload";
	//生成uuid
	UUID uuid = UUID.randomUUID();
	//重写保存文件的文件名
	String substring = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
	String randomFileName = uuid+substring;
	//保存图片到绝对路径上
	File destFile = new File(realPath+"/"+randomFileName);
	FileUtils.copyFile(titleImgFile, destFile);
	//把保存路径保存到promotion中
	model.setTitleImg(ServletActionContext.getRequest().getContextPath()
			+ "/upload/" + randomFileName);
	//调用业务层保存数据
	ps.save(model);
		return SUCCESS;

	}
// 后台分页显示
@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
public String pageQuery() {
	Pageable pageable = new PageRequest(page-1, rows);
	//调用业务层查询数据
	Page<Promotion>  pageDate = ps.findPageData(pageable);
	//压入值栈
	
	pushPageDataToValueStack(pageDate);
	return SUCCESS;

}
}
